<template>
  <div id="intfconfig">
    <Splitpanes style="height: 100%">
      <Pane size="100">
        <vxe-toolbar perfect>
          <template #buttons>
            <el-form :inline="true"
              class="demo-form-inline">
              <el-form-item
                v-for="(item, idx) in intfItemSettingsList.filter((data) => data.where == 0)"
                :key="idx">
                <el-input clearable
                  :placeholder="item.paramnotes"
                  v-model="item.value"></el-input>
              </el-form-item>
            </el-form>
            <vxe-button type="text"
              status="primary"
              icon="vxe-icon-refresh"
              content="刷新"
              @click="handleSearch"
              class="button-blue"></vxe-button>
            <vxe-button type="text"
              status="info"
              icon="vxe-icon-feedback"
              content="预览SQL"
              class="text-cyan button-blue"
              @click="getSql"></vxe-button>
            <vxe-button type="text"
              status="primary"
              icon="vxe-icon-send-fill"
              content="执行查询"
              @click="execSelect"
              class="button-blue"></vxe-button>
            <vxe-button type="text"
              status="success"
              icon="vxe-icon-check"
              content="校准数据"
              @click="checkData"
              class="button-blue"></vxe-button>
            <vxe-button type="text"
              status="warning"
              icon="vxe-icon-save"
              content="数据导入"
              @click="downloadData"
              class="button-blue"></vxe-button>
          </template>
        </vxe-toolbar>
        <el-scrollbar
          style="height: calc(100% - 40px)">
          <div class="textareaClass">
            <el-input
              v-model="currentRow.methodData"
              :rows="5"
              type="textarea" />
          </div>
          <div class="textareaClass">
            <vxe-grid ref="abcdefg"
              :loading="qloading"
              v-bind="dynamicDataList">
            </vxe-grid>

          </div>
        </el-scrollbar>
      </Pane>
    </Splitpanes>
  </div>
  <el-dialog title="参数值设定"
    :show-close="false"
    v-model="showParamDialog"
    width="1000px"
    :close-on-click-modal="false"
    destroy-on-close
    v-if="showParamDialog">
    <div class="tableTargetBody"
      style="height: 500px">
      <vxe-table ref="extParamsTableRef"
        :border="'inner'"
        show-header-overflow
        :data="extParamList"
        :row-config="{ isCurrent: true }"
        :column-config="{ resizable: true }"
        :edit-config="{ trigger: 'click', mode: 'cell' ,showIcon:false}"
        height="auto"
        class="mytable-scrollbar">
        <vxe-column type="seq"
          width="30"
          title="#"></vxe-column>

        <vxe-column field="extCode"
          title="外源参数" width="140">
        </vxe-column>
        <vxe-column field="symbol"
          title="比较" width="100">
          <template #default="{row}">
            <div>
              {{emSymbolArr.filter(data => data.value === row.symbol)[0].label}}
            </div>
          </template>
          <template #edit="{ row }">
            <vxe-select
              v-model="row.symbol"
              transfer>
              <vxe-option
                v-for="item in emSymbolArr"
                :key="item.value"
                :value="item.value"
                :label="item.label"></vxe-option>
            </vxe-select>
          </template>
        </vxe-column>
        <vxe-column field="inCodeNo"
          title="入参" width="80">
        </vxe-column>
        <vxe-column field="inCodeNa"
          title="参数名称" width="85">
        </vxe-column>
        <vxe-column field="extCodeDtype"
          title="外源参数类型" width="70">
          <template #default="{ row }">
            <span>{{ formatCommon(coloumTypeList, row.extCodeDtype) }}</span>
          </template>
        </vxe-column>
        <vxe-column field="inCodeDtype"
          title="入参数据类型" width="70">
          <template #default="{ row }">
            <span>{{ formatCommon(coloumTypeList, row.inCodeDtype) }}</span>
          </template>
        </vxe-column>
        <vxe-column field="inCodeDes"
          title="入参说明" width="100">
        </vxe-column>
        <vxe-column field="relation"
          title="关系" width="65">
          <template #default="{row}">
            <div>
              {{[{ value: 'and', label: '并且' },{ value: 'or', label: '或者' }].filter(data => data.value === row.relation)[0].label}}
            </div>
          </template>
        </vxe-column>
        <vxe-column field="inValue"
          title="入参值" :edit-render="{}"
          width="100">
          <template #edit="{ row }">
            <vxe-input
              v-model="row.inValue"
              type="text"
              placeholder="入参值"></vxe-input>
          </template>
        </vxe-column>
      </vxe-table>
      <div
        class="dialog-footer flex right justify-end">
        <el-button type="primary"
          @click="execExtParam('extParamsTableRef')">确定</el-button>
        <el-button
          @click="closeDialog('extParamsTableRef')">取消</el-button>
      </div>

    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { ElMessage } from 'element-plus';
// import { fa } from 'element-plus/es/locale';
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '../../../utils/CommonMessage';
import { AppStore } from '../../../stores/store';
// import saveAs from 'file-saver';
import { defineProps } from 'vue';
import { enums } from '@/enums/enumerator.js';
import { VxeGridProps } from 'vxe-table';

defineExpose({ initPage });
let store = AppStore();
let { proxy }: any = getCurrentInstance();
let modulePoitPre = reactive([]);
// 当前屏幕高度
let conHeight = ref(document.documentElement.clientHeight || document.body.clientHeight);
let leftpane = ref('100');
let rightpane = ref('0');
let textarea = ref('');
//关键字
let keywords = ref('');
let loading = ref(false);
// 接口表格数据
let intfMainList = reactive([]);
let extParamList: any[] = reactive([]);
let maindialogVisible = ref(false);
let currentRow: any = reactive({});
let emSymbolArr = reactive(enums.emSymbol);
let coloumTypeList = reactive([]);
let qloading = ref(false); //右侧质控表格加载+刷新

let dynamicDataList: any = reactive({});

let mainform = reactive({
  id: '',
  code: '', //编码
  name: '', //名称
  intfId: '', //所属模块
  type: '', //类型
  state: 0, //状态
  sn: 0, //排序号
  //数据库
  source: '', //外源表
  standard: '', //标准表
  template: '', //校准模板
  settings: '' //配置细项
});
let intfItemSettingsList = reactive([]);
onMounted(() => {
  //handleSearch();
});
//批量获取字典
async function getDictItemsList() {
  coloumTypeList.length = 0;
  let dictTreeTypeCodes: any = ['interfaceColoumType'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const severityType = dictTreeTypeItems.data.find((item) => item.code === 'interfaceColoumType');
  coloumTypeList.push(...severityType.detailDataList);
}

/**页面初始化 */
function initPage(row: any) {
  getDictItemsList();
  Object.assign(currentRow, row);
  Object.assign(dynamicDataList, {
    border: true,
    height: 300,
    align: null,
    columnConfig: {
      resizable: true
    },
    columns: [],

    data: []
  });
}

// 点击刷新
function handleSearch() {
  let intfParam = reactive({
    id: ''
  });
  intfItemSettingsList.length = 0; //放入数据前清空数组
  proxy.$http.post('/api/sys/getIntfItem', intfParam).then((res: any) => {
    if (res.status.code === 1) {
      const data = res.data;

      setvalue(mainform, data);
      if (mainform.settings) {
        const records = JSON.parse(mainform.settings);
        intfItemSettingsList.push(...records);
      }
      loading.value = false;
    } else {
      VXETable.modal.message({ content: res.status.msg, status: 'error' });
      return;
    }
  });
}
//新建
async function handleAdd() {
  clearmainform();
  maindialogVisible.value = true;
  // intfMainList.push(record);
}
async function saveRow() {
  if (!mainform.id) {
    mainform.id = '2000' + mainform.sn;
    intfMainList.push(mainform);
  } else {
    for (let i = intfMainList.length - 1; i >= 0; i--) {
      if (mainform.id == intfMainList[i].id) {
        setvalue(intfMainList[i], mainform);
        break;
      }
    }
  }
  localStorage.setItem('intfItemList', JSON.stringify(intfMainList));
  VXETable.modal.message({ content: '操作成功', status: 'success' });
  maindialogVisible.value = false;
  setTimeout(() => {
    handleSearch();
  }, 500);
}
async function editRow({ row }) {
  clearmainform();
  setvalue(mainform, row);
  maindialogVisible.value = true;
}
function setvalue(form, row) {
  form.id = row.id;
  (form.code = row.code), //编码
    (form.name = row.name), //名称
    (form.intfId = row.intfId), //所属模块
    (form.type = row.type), //类型
    (form.state = row.state), //状态 禁用/调试/启用
    (form.sn = row.sn), //排序号
    //数据库
    (form.source = row.source), //数据库地址
    (form.standard = row.standard); //数据库名称
  form.template = row.template; //校准模板
  form.settings = row.settings; //配置细项
}
function clearmainform() {
  mainform.id = '';
  (mainform.code = ''), //编码
    (mainform.name = ''), //名称
    (mainform.intfId = ''), //所属模块
    (mainform.type = ''), //类型
    (mainform.state = 0), //状态 禁用/调试/启用
    (mainform.sn = 0), //排序号
    //数据库
    (mainform.source = ''), //外源表
    (mainform.standard = ''); //标准表
  mainform.template = ''; //校准模板
  mainform.settings = ''; //配置细项
}
// 点击修改保存
async function saveList() {
  // 获取表格实例
  let $Xtable = proxy.$refs.moduleTable;

  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
      return p.id !== '';
    });

    // const InsertRecords = await $Xtable.getInsertRecords().filter((m: any) => {
    //   return m.id === '';
    // });
    // 拿到数组中没有id的数据为新增
    const InsertRecords = intfMainList.filter((e) => {
      return e.id === '';
    });


    // 遍历发起请求  将筛选出有id的每一个对象（修改过的） 作为参数传递给后端
    updateRecords.forEach((e) => {
      let moduleAddParam = e;
    });

    // 新增
    InsertRecords.forEach((e) => {
      const moduleAddParam = e;
      moduleAddParam.id = '1';
    });
    // localStorage.setItem('activeIndex', JSON.parse(JSON.stringify(this.intfMainList)));
    localStorage.setItem('intfItemList', JSON.stringify(intfMainList));
    VXETable.modal.message({ content: '操作成功', status: 'success' });
    setTimeout(() => {
      handleSearch();
    }, 500);
  } else {
    return;
  }
}
// 点击删除
async function handleDelete() {
  let $Xtable = proxy.$refs.moduleTable;
  let selectRows = $Xtable.getCheckboxRecords();
  if (selectRows <= 0) {
    VXETable.modal.message({ content: `请勾选要删除的数据`, status: 'warning' });
    return;
  }
  const type = await VXETable.modal.confirm('您确定要删除吗？');
  if (type != 'cancel') {
    for (const item of selectRows) {
      for (let i = intfMainList.length - 1; i >= 0; i--) {
        if (item.code == intfMainList[i].code) {
          intfMainList.splice(i, 1);
          break;
        }
      }
    }
    saveList();
  }
}
// 点击行
function moduleRowClick({ row, rowIndex }) {
  leftpane.value = '25';
  rightpane.value = '75';
}

function getSql() {
  textarea.value = 'select ';
  for (const item of intfItemSettingsList) {
    textarea.value = textarea.value + item.outsource + ' as ' + item.standard + ' , ';
  }
  textarea.value = textarea.value + '1' + ' as ' + 'ok where 1=1';
  for (const item of intfItemSettingsList.filter((data) => data.where == 0)) {
    textarea.value = textarea.value + ' and ' + item.outsource + " = '" + item.value + "' ";
  }
  for (const item of intfItemSettingsList.filter((data) => data.ishave == 0)) {
    textarea.value = textarea.value + ' and ' + item.outsource + ' is not null and ' + item.outsource + " <> '' ";
  }
}
let showParamDialog = ref(false); //中间质控靶值设定弹框展示状态

let infoList = reactive([]);
function execSelect() {
  const data = {};
  infoList.length = 0;
  for (const item of intfItemSettingsList) {
    if (item.value) {
      data[item.standard] = item.value;
    } else {
      data[item.standard] = '测试';
    }
  }
  setTimeout(() => {
    infoList.push(data);
  }, 500);
  showParamDialog.value = true;
  proxy.$nextTick(() => {
    findSysInterfaceMethodExtParams();
  });

  /**获取入参参数对照 */
  function findSysInterfaceMethodExtParams() {
    extParamList.length = 0;
    const url = '/api/sys/sys-interface-meth-ext-param/findSysInterfaceMethExtParamList';
    proxy.$http
      //注意此处的数据条数
      .get(url, {
        params: { interfaceMethodId: currentRow.id }
      })
      .then((res: any) => {
        Object.assign(extParamList, res.data);
      })
      .catch((err: any) => {
        VxeMessage('获取表格数据异常', VxeNotifyType.error);
      });
  }
}
function checkData() {
  const data = {};
  infoList.length = 0;
  for (const item of intfItemSettingsList) {
    if (item.value) {
      data[item.standard] = item.value;
    } else {
      data[item.standard] = '测试OK';
    }
  }
  setTimeout(() => {
    infoList.push(data);
    textarea.value = '数据校准完成';
  }, 500);
}
function downloadData() {
  setTimeout(() => {
    textarea.value = '数据导入完成！！！';
  }, 500);
}
function execExtParam() {
  qloading.value = true;
  const data = { methodId: currentRow.id, extParamList: extParamList };
  const url = '/api/sys/sys-interface-meth-ext-param/execExtParam';
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      const dataObj = res.data[0];
      for (const key in dataObj) {
        dynamicDataList.columns.push({ field: key, title: key, width: 100 });
      }
      Object.assign(dynamicDataList.data, res.data);
      qloading.value = false;
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
      qloading.value = false;
    });
  closeDialog();
}
// 弹框取消按钮
function closeDialog() {
  showParamDialog.value = false;
}

/**数据类型显示文本 */
function formatCommon(arr, value) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}
</script>
<style lang="scss" scoped>
#intfconfig {
  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }
  .el-form-item {
    margin-right: 10px;
  }
  .textareaClass {
    margin: 0 10px 10px 10px;
  }
}
</style>
